/**
 * 
 */
package com.rmdc.simop.commons.model.dao.hibernate;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.rmdc.simop.commons.model.dao.BaseDAO;


public abstract class BaseDAOHibernateImpl<Entity extends Serializable> extends
		HibernateDaoSupport implements BaseDAO<Entity> {

	protected Class<Entity> entityClass = getEntityClass();

	protected abstract Class<Entity> getEntityClass();

	@SuppressWarnings("unchecked")
	public List<Entity> findByCodigo(String codigo) {
		String queryString = "from " + entityClass.getSimpleName()
				+ " as model where lower(model.codigo"
				+ getEntityClass().getSimpleName() + ") LIKE '"
				+ codigo.toLowerCase() + "%'";
		return getHibernateTemplate().find(queryString);
	}


	@SuppressWarnings("unchecked")
	public List<Entity> findByProperty(String valor, String nombrePropiedad) {
		String queryString = "from " + entityClass.getSimpleName()
				+ " as model where lower(model." + nombrePropiedad + ") LIKE '"
				+ valor.toLowerCase() + "%'";
		return getHibernateTemplate().find(queryString);
	}

	@SuppressWarnings("unchecked")
	public Entity readByCodigo(String codigo) {
		String queryString = "from " + getEntityClass().getSimpleName()
				+ " as model where model.codigo" + entityClass.getSimpleName()
				+ " ='" + codigo + "'";
		List li = (List) getHibernateTemplate().find(queryString);
		for (Iterator iterator = li.iterator(); iterator.hasNext();) {
			Entity name = (Entity) iterator.next();
			return name;
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public Entity readById(Integer id) {
		String queryString = "from " + entityClass.getSimpleName()
				+ " as model where model.id" + entityClass.getSimpleName() + "="
				+ id;
		List l = getHibernateTemplate().find(queryString);
		for (Iterator iterator = l.iterator(); iterator.hasNext();) {
			Entity name = (Entity) iterator.next();
			return name;
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<Entity> findAll() {
		String queryString = "from " + getEntityClass().getSimpleName();
		return getHibernateTemplate().find(queryString);

	}

	public void delete(Entity object) {
		getHibernateTemplate().delete(object);		
	}

	public void deleteByCodigo(String codigo) {
		Object obj = readByCodigo(codigo);
		getHibernateTemplate().delete(obj);
		
	}

	public void deleteById(Integer id) {
		Object obj = readById(id);
		getHibernateTemplate().delete(obj);
		
	}
	public void create(Entity object) {
		getHibernateTemplate().save(object);
	}
	public void update(Entity object) {
		getHibernateTemplate().update(object);
	}

}
